#include "Game.h"

/* Default constructor */
Game::Game(){
    init();
    }

/* Get a string representation of the game */
string Game::getGameInString(){
    unsigned int blockCnt = 0;
    string field = "";
    for (int y = LVL_HEIGHT-1; y > -1; y--){
        for (unsigned int x = 0; x < LVL_WIDTH; x++){
            //Drawing block if necessary
            if (((x >= _curBlockX) && (x <= _curBlockX+3)) &&
                ((y <= _curBlockY) && (y >= _curBlockY-3))){
                //Draw block
                field += toString(_curBlock->getBlockPos(blockCnt++));
            }
            else{
                //Put the value into the string
                field += toString(_level.getPosition(x,y));
            }
            }
        field += "\n";    //\r\n for Windows, \n for Unix
        }
    return field;
    }

/* Iniatilize game */
void Game::init(){
    _level = Level();        //Start with a nice clean level
    _started = false;
    _score = 0;
    _speed = 1;

    //Load available Blocks
    _blocks.push_back(new Bar());
    _blocks.push_back(new Block());

    //Blocks
    _nextBlock = NULL;  //Make sure the blocks are getting filled
    //pickBlock();
    }

/* update the blocks, the next block becomes current and next becomes a new one */
void Game::pickBlock(){
    unsigned int block;
    if (_nextBlock == NULL){
        block = (1*rand())/(RAND_MAX + 1.0);
        _nextBlock = (Blocks*)_blocks[block];
        }
    //Now fill the current and get a new for the next
    _curBlock = _nextBlock;
    _nextBlock = _blocks[(1*rand())/(RAND_MAX + 1.0)];
    }

/* Start the game */
void Game::startGame(){
    _started = true;
    //Temporately
    update();
    }

/* Update gamestats */
void Game::update(){
    if (_falling){
        //Then move current block down
        _curBlockY--;
    } else {
        //Pick block and move down
        pickBlock();
        _curBlockX = 3;
        _curBlockY = 19;
        _falling = true;
    }

    //collision detection (including bottom)
    bool gotBlocksL4 = false;
    for(unsigned int y=4; y > 0; y--){
        for(unsigned int x=0; x < 3; x++){
/*            if ((y == 4) && ((_level.getPosition(_curBlockX + x, _curBlockY + y) == BLOCK)){
                _gotBlocksL4 = true;
                }
            if ((y < 4) && gotBlocksL4){    //There are blocks below the falling block.
                    if ((_curBlock.getBlockPosXY(x,y) == BLOCK) && (_level.getPosition(_curBlockX + x, _curBlockY + 4) == BLOCK){
                        //Collision!

                        }
                }*/
        }
    }

    //if CD then falling = false
    }

Game::~Game(){
    //Delete blocks that are in the memory
    for(unsigned int i = 0; i < _blocks.size(); i++){
            delete _blocks[i];
        }
}
